package com.example.auth2.util;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.sql.rowset.serial.SerialException;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 常用对象处理类
 * @author Mr.Liu
 */
public class DfUtils {
    
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
    
    public static String getYYYYMMDD(Object obj){
    	if(obj == null){
            return "";
        }
    	if(obj instanceof Date){
            return sdf2.format((Date)obj);
        }
        
        return obj.toString().trim();
    }
    
    public static String trim(Object obj){
        if(obj == null){
            return "";
        }
        if(obj instanceof String){
            if(!StringUtils.isNotBlank((String)obj)){
                return "";
            }
            if(obj.toString().equals("null") || obj.toString().equals("NULL") || obj.toString().equals("undefined")){
            	return "";
            }
        }
        if(obj instanceof XMLGregorianCalendar){
            Date date =  ((XMLGregorianCalendar)obj).toGregorianCalendar().getTime();
            return sdf.format(date);
        }
        if(obj instanceof Date){
            return sdf.format((Date)obj);
        }
        
        return obj.toString().trim();
    }
    
    public static String replaceBlank(Object str) {
    	String newstr = trim(str);
		String dest = "";
		if (str!=null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(newstr);
			dest = m.replaceAll("");
		}
		return dest;
	}
    
    public static Double doubleVal(Object obj){
        if(obj == null){
            return 0D;
        }
        if(obj instanceof String){
        	if("".equals(obj)){
        		return 0D;
        	}
            return Double.valueOf((String) obj);
        }
        if(obj instanceof Long){
            return Double.valueOf((Long) obj);
        }
        if(obj instanceof Integer){
            return Double.valueOf((Integer) obj);
        }
        if(obj instanceof BigDecimal){
            return ((BigDecimal)obj).doubleValue();
        }
        return Double.valueOf(obj.toString());
    }
    public static Long longVal(Object obj){
        if(obj == null){
            return null;
        }
        if(obj instanceof String){
            if(StringUtils.isBlank((String)obj)){
                return null;
            }
            if("".equals(obj)){
        		return null;
        	}
            if(obj.equals("是")){
                return 1L;
            }else if(obj.equals("否")){
                return 0L;
            }
            return Long.valueOf((String) obj);
        }
        if(obj instanceof Long){
            return Long.valueOf((Long) obj);
        }
        if(obj instanceof Integer){
            return Long.valueOf((Integer) obj);
        }
        if(obj instanceof BigDecimal){
            return ((BigDecimal)obj).longValue();
        }
        return Long.valueOf(obj.toString());
    }
    
    public static Date dateVal(Object obj) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        if(trim(obj).equals("")){
            return null;
        }
        
        if(obj == null){
            return null;
        }
        
        if(obj instanceof Date){
            return (Date) obj;
        }
        if(obj instanceof String){
            
            if(obj.toString().length() <=10){
                sdf = new SimpleDateFormat("yyyy-MM-dd");
            }else{
            	if(obj.toString().contains("T")){
            		if(obj.toString().length() >= 19){
            			String newStr = obj.toString().substring(0,18).replace("T"," ");
            			return sdf.parse(newStr);
            		}
            	}
            }
            return sdf.parse((String) obj);
        }
        if(obj instanceof Calendar){
            return ((Calendar)obj).getTime();
        }
        if(obj instanceof XMLGregorianCalendar){
            return ValueConvert.xMLGregorianCalendarToDate((XMLGregorianCalendar)obj);
        }
        
        return (Date) obj;
    }
    
    public static XMLGregorianCalendar xMLGregorianCalendarVal(Object obj) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        
        if(obj == null){
            return null;
        }
        
        if(obj.toString().length() <=10){
        	Date obj_d = sdf2.parse((String)obj);
            return ValueConvert.DateToXMLGregorianCalendar((Date)obj_d);
        }
        if(obj instanceof String){
            Date obj_d = sdf.parse((String)obj);
            return ValueConvert.DateToXMLGregorianCalendar((Date)obj_d);
        }
        if(obj instanceof Date){
            return ValueConvert.DateToXMLGregorianCalendar((Date)obj);
        }
        if(obj instanceof XMLGregorianCalendar){
            return (XMLGregorianCalendar)obj;
        }
        return (XMLGregorianCalendar) obj;
    }

    
    public static BigDecimal bigDecimalVal(Object obj) throws Exception{
        if(obj == null){
            return null;
        }
        if(obj instanceof BigDecimal){
            return (BigDecimal) obj;
        }
        if(obj instanceof String){
            return new BigDecimal((String)obj);
        }
        if(obj instanceof Long){
            return new BigDecimal((Long)obj);
        }
        if(obj instanceof Double){
            return new BigDecimal((Double)obj);
        }
        return (BigDecimal) obj;
    }
    
    public static Calendar calendarVal(Object obj) throws Exception{
        if(obj == null){
            return null;
        }
        if(obj instanceof Date){
            return ValueConvert.getCalendarVal((Date)obj);
        }
        return (Calendar) obj;
    }
    
    public static Boolean booleanVal(Object obj) throws Exception{
        if(obj == null){
            return Boolean.FALSE;
        }
        if(obj instanceof String){
        	if(((String)obj).equals("1") || ((String)obj).equals("true")){
                return Boolean.TRUE;
            }else{
            	return Boolean.FALSE;
            }
        }
        if(obj instanceof Long){
        	if((Long)obj == 1L){
        		return Boolean.TRUE;
        	}else{
        		return Boolean.FALSE;
        	}
        }
        return (Boolean) obj;
    }
    
    public static Integer integerVal(Object obj) throws Exception{
        if(obj == null){
            return null;
        }
        return new Integer(obj.toString());
    }
    
    public static String toObjsString(Object[] obj){
        if(null == obj){
            return null;
        }
        String rs = "";
        for (int i = 0; i < obj.length; i++) {
            String s  = obj[i]!=null?obj[i].toString():null;
            //if(null != obj[i]){
               // s = obj[i].toString();
            //}
            if(i != obj.length-1){
                s+=",";
            }
            rs+=s;
        }
        return rs;
        
    }
    
    /**
     * Clob读取和转换
     * 2017-4-26
     * @param cl
     * @return
     * @throws SQLException 
     * @throws SerialException 
     */
    public static Clob StrToClob(String cl) throws SerialException, SQLException {
        if(cl == null){
            return null;
        }
        if(!StringUtils.isNotBlank(cl)){
            return new javax.sql.rowset.serial.SerialClob("".toCharArray());
        }
        return new javax.sql.rowset.serial.SerialClob(cl.toCharArray());
    }
    
    
    
    public static String ClobToStr(Clob clob) throws SQLException, IOException {
        String reString = "";
        //得到流
        Reader is = clob.getCharacterStream();
        BufferedReader br = new BufferedReader(is);
        String s = br.readLine();
        StringBuffer sb = new StringBuffer();
        //执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
        while (s != null) {
            sb.append(s);
            s = br.readLine();
        }
        if (null != br) {
        	br.close();
		}
        reString = sb.toString();
        return reString;
    }
    
    public static boolean isNotBank(Object obj){
    	boolean rs = Boolean.TRUE;
    	if(DfUtils.trim(obj).equals("") || DfUtils.trim(obj).equals("null")){
    		rs = Boolean.FALSE;
    	}
		return rs;
    }
    
    public static boolean isBank(Object obj){
    	boolean rs = Boolean.TRUE;
    	if(!DfUtils.trim(obj).equals("")){
    		rs = Boolean.FALSE;
    	}
		return rs;
    }
    
    /**
     * 中文解码
     * @param str
     * @return
     */
    public static String URLDecode(String str){
    	String rsMsg = "";
    	try {
    		rsMsg = URLDecoder.decode(URLDecoder.decode(str,"utf-8"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return rsMsg;
    }
    
    /**
     * 中文编码
     * @param str
     * @return
     */
    public static String URLEncode(String str){
    	String rsMsg = "";
    	try {
    		rsMsg = URLEncoder.encode(URLEncoder.encode(str,"utf-8"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return rsMsg;
    }
    
    /**
	 * 复制源对象和目标对象的属性值(除ID)
	 * source源对象
	 * target新对象
	 * objs不复制的属性
	 */
	public static void copyObject(Object source, Object target,String[] objs) throws Exception{
		Class sourceClass = source.getClass();//得到源对象的Class
		getClassFieldAndMethod(source,target,sourceClass,objs,false);
	}
	
	public static void copyObjectContainNull(Object source, Object target,String[] objs) throws Exception{
		Class sourceClass = source.getClass();//得到源对象的Class
		getClassFieldAndMethod(source,target,sourceClass,objs,true);
	}
	
	public static void copyMapToObject(Object source, Map<String, Object> map, String[] objs) throws Exception{
		setClassFiled(source,map,objs);
	}
	
	private static void setClassFiled(Object source,Map<String, Object> map,String[] objs) throws Exception {
		Class sourceClass = source.getClass();//得到源对象的Class
	    Field[] sourceFields = sourceClass.getDeclaredFields();//得到源Class对象的所有属性
	    for (Field sourceField : sourceFields) {
	    	String name = sourceField.getName();//属性名
	    	//不复制属性
	    	if(objs != null && objs.length > 0){
				for (int i = 0; i < objs.length; i++) {
					if(name.equals(objs[i])){
						break;
					}
				}
			}
	    	sourceField.setAccessible(true);
	        Class type = sourceField.getType();//属性类型
	        Object value = map.get(name);
	        if(DfUtils.isNotBank(value)){
	        	String methodName = name.substring(0, 1).toUpperCase() + name.substring(1);
		        Method setMethod = sourceClass.getMethod("set" + methodName, type);//属性对应的set方法
				setMethod.invoke(source, value);//执行目标对象的set方法
	        }
	    }
	}
	
	 /**
	  * 
	  * @param source 源对象
	  * @param target 目标对象
	  * @param sourceClass 源对象class
	  * @param objs 不复制的属性
	  * @param isCopyNull 是否复制数据为空的属性
	  * @throws Exception
	  */
    private static void getClassFieldAndMethod(Object source,Object target,Class sourceClass,String[] objs,boolean isCopyNull) throws Exception {
		Class targetClass = target.getClass();//得到目标对象的Class
		
	    Field[] sourceFields = sourceClass.getDeclaredFields();//得到源Class对象的所有属性
	    Field[] targetFields = targetClass.getDeclaredFields();//得到目标Class对象的所有属性
	    for (Field sourceField : sourceFields) {
	    	sourceField.setAccessible(true);
	        String name = sourceField.getName();//属性名
	        Class type = sourceField.getType();//属性类型
			String methodName = name.substring(0, 1).toUpperCase() + name.substring(1);
			Method getMethod = sourceClass.getMethod("get" + methodName);//得到属性对应get方法
			Object value = getMethod.invoke(source);//执行源对象的get方法得到属性值
//			System.out.println("get" + methodName +"==="+value);
			for(Field targetField : targetFields){
				String targetName = targetField.getName();//目标对象的属性名
				boolean isCheck = false;
				if(objs != null && objs.length > 0){
					for (int i = 0; i < objs.length; i++) {
						if(targetName.equals(objs[i])){
							isCheck = true;
							break;
						}
					}
				}
				if(!isCheck && targetName.equals(name)){
					if(isCopyNull || (!isCopyNull && value != null)){
						Method setMethod = targetClass.getMethod("set" + methodName, type);//属性对应的set方法
						setMethod.invoke(target, value);//执行目标对象的set方法
					}
				}
			}
	    }
	    if (sourceClass.getSuperclass() != null) {
	    	//递归查询父类
	        getClassFieldAndMethod(source,target,sourceClass.getSuperclass(),objs,isCopyNull);
	    }
	}
	
	/**
     * 获取当前时间前day的日期
     * @param date
     * @return
     */
    public static Date getNextDay(Date date,int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -day);
        date = calendar.getTime();
        return date;
    }
    
    /**
     * 获取当前时间前year的日期（前几年）
     * @param date
     * @param year
     * @return
     */
    public static Date getNextYear(Date date,int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, -year);
        date = calendar.getTime();
        return date;
    }
    
    
    /**
     * JSONArray转换成List<Map<String,Object>>
     * @param ja
     * @return
     */
   /* public static List<Map<String,Object>> jsonArraytoList(String ja){
    	
    	JSONArray jsonArray = JSONArray.fromObject(ja);
		Iterator<Object> it = jsonArray.iterator();
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String,Object> map = null;
		while (it.hasNext()) {
			map = new HashMap<String,Object>();
			JSONObject json = (JSONObject) it.next();
			Iterator jsonIt = json.keys();
    		while(jsonIt.hasNext()){
    			String key = String.valueOf(jsonIt.next());
    			String value = DfUtils.trim(json.get(key));
    			map.put(key, value);
    		}
    		list.add(map);
		}
    	return list;
    }*/
    
    /**
     * 将jsonObject转换成map集合
//     * @param jo
     * @return
     */
    /*public static Map<String,Object> jsonObjecttoMap(String jo){
    	//由于fromObject会将字符串中的反斜杠直接过滤，再fromObject之前用一个字符替换，完了再替换回来
    	jo = jo.replaceAll("\\\\", "char_91");
    	JSONObject json = JSONObject.fromObject(jo);
		Iterator jsonIt = json.keys();
		Map<String,Object> map = new HashMap<String, Object>();
		while(jsonIt.hasNext()){
			String key = String.valueOf(jsonIt.next());
			String value = DfUtils.trim(json.get(key)).replaceAll("char_91", "\\\\");
			map.put(key, value);
		}
		return map;
    }
    */
    
    public static String getObjsVal(Object[] objs){
    	String rs = "";
    	if(objs != null){
    		for (int i = 0; i < objs.length; i++) {
    			rs+=objs[i];
    			if(i != objs.length -1 ){
    				rs+=",";
    			}
			}
    	}
		return rs;
    }
    
    /**
     * 获取大写字母位置数组
     * @param filedName
     * @return
     */
    public static Object[] getDBCloumnByfiledName(String filedName){
    	if(isNotBank(filedName)){
    		List<Integer> indexs = new ArrayList<Integer>();
    		//1.获取大写字母对应序号
    		char[] chars = filedName.toCharArray();
    		for (int i = 0; i < chars.length; i++) {
				char c = chars[i];
				if(Character.isUpperCase(c)){
					indexs.add(i);
	    		}
			}
    		return indexs.toArray();
    	}
		return null;
    }
   
    /**
     * 根据字段字母大写将字段转化为数据库字段名称
     * @param filedName
     * @return
     * @throws Exception
     */
   /* public static String getDBCloumByIndex(Class modelClass,String filedName) throws Exception{
    	if(DfUtils.isBank(filedName)){
    		return null;
    	}
    	LinkedHashMap<String,String> mapper = OrmClassCacheTools.getClassMaps(modelClass);
    	if(null != mapper.get(filedName)){
    		return mapper.get(filedName);
    	}
		return filedName.toUpperCase();
    }*/
    
    public static String getDBCloumByIndex(String filedName) throws Exception{
    	Object[] objs = getDBCloumnByfiledName(filedName);
    	StringBuffer sbf = new StringBuffer(10);
    	if(objs != null && objs.length > 0){
    		int k = 0;
    		for (int i = 0; i < objs.length; i++) {
				int index = DfUtils.integerVal(objs[i]);
				if(index != 0){
					sbf.append(filedName.substring(k, index));
					k=index;
					sbf.append("_");
					if(i == objs.length-1){
						sbf.append(filedName.substring(index, filedName.length()));
					}
				}
			}
    	}else{
    		sbf.append(filedName);
    	}
		return sbf.toString();
    }
    
    /**
     * 字符串xml转换为map
     * @param request
     * @return
     */
	public static Map<String, Object> buildStringToMap(String request) {
		Map<String,Object> map = new HashMap<String,Object>();  
        Document doc;  
        try {  
            doc = DocumentHelper.parseText(request);  
            Element el = doc.getRootElement();  
            map = recGetXmlElementValue(el,map);  
        } catch (DocumentException e) {  
            e.printStackTrace();  
        }  
        return map; 
	}
	
	/**
     * map转换为字符串xml
     * @param rsMap
     * @return
     */
	public static String bulidMapToString(Map<String, Object> rsMap) {
		StringBuffer sb = new StringBuffer("");  
        sb.append("<xml>");  
        Set<String> set = rsMap.keySet();  
        for(Iterator<String> it=set.iterator(); it.hasNext();){  
            String key = it.next();  
            Object value = rsMap.get(key);  
            sb.append("<").append(key).append(">");  
            sb.append(value);  
            sb.append("</").append(key).append(">");  
        }  
        sb.append("</xml>");  
        return sb.toString();  
	}
	
	/**
     * map转换为List
     * @param rsMap
     * @return
     */
	public static List<Object> bulidMapToList(Map<String, Object> rsMap) {
		List<Object> paramList = new ArrayList<Object>();
		if(null != rsMap && !rsMap.isEmpty()){
			for (String key : rsMap.keySet()) {
				paramList.add(rsMap.get(key));
			}
		}
		return paramList;
	}
    
	
	/**  
     * 循环解析xml  
     * @param ele  
     * @param map  
     * @return  
     */  
    @SuppressWarnings({ "unchecked" })  
    private static Map<String, Object> recGetXmlElementValue(Element ele, Map<String, Object> map){  
        List<Element> eleList = ele.elements();  
        if (eleList.size() == 0) {  
            map.put(ele.getName(), ele.getTextTrim());  
            return map;  
        } else {  
            for (Iterator<Element> iter = eleList.iterator(); iter.hasNext();) {  
                Element innerEle = iter.next();  
                recGetXmlElementValue(innerEle, map);  
            }  
            return map;  
        }  
    } 
    
    /**
     * 比较两个时间的大小，只精确到日期
     * d1<=d2 返回true
     * @param d1
     * @param d2
     * @return
     */
   /* public static boolean compareDate(Date d1,Date d2){
    	String d1Str = DateTime.convertDateTime_YYYYMMDD(d1);
    	String d2Str = DateTime.convertDateTime_YYYYMMDD(d2);
    	
    	d1 = DateTime.parseDateTime_YYYYMMDD(d1Str);
    	d2 = DateTime.parseDateTime_YYYYMMDD(d2Str);
    	
    	if(d1.getTime() <= d2.getTime()){
    		return true;
    	}
    	return false;
    }*/
    
    /**
     * 查询最近10年
     * @return
     */
    public static List<Map<String,Long>> findTenYear() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Long year = DfUtils.longVal(sdf.format(date));
        List<Map<String,Long>> list = new ArrayList<Map<String,Long>>();
        for(int i = 0;i<10;i++){
            Map<String,Long> map = new HashMap<String,Long>();
            if(i == 0){
                map.put("year", year);
                list.add(map); 
            }else{
                year = year-1;
                map.put("year", year);
                list.add(map); 
            }
        }
        return list;
    }
    
    /**
     * 查询当前时间前后几年
     * @param m 前几年
     * @param n 后几年
     * @return
     */
    public static List<Map<String,Long>> findAroundYear(int m,int n){
    	Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Long year = DfUtils.longVal(sdf.format(date));
        List<Map<String,Long>> list = new ArrayList<Map<String,Long>>();
        for(int i = 1;i < n;i++){
        	Map<String,Long> map = new HashMap<String,Long>();
        	if(i == 1){
        		year = year+n-1;
        	}else{
        		year = year-1;
        	}
            map.put("year", year);
            list.add(map); 
        }
        year = DfUtils.longVal(sdf.format(date));
        for(int i = 0;i < m;i++){
        	Map<String,Long> map = new HashMap<String,Long>();
            if(i == 0){
                map.put("year", year);
                list.add(map); 
            }else{
                year = year-1;
                map.put("year", year);
                list.add(map); 
            }
        }
        return list;
    }
    
    
    /**
     * 提供截取字符串方法，多余的用...展示
     * @param inS
     * @param length
     * @return
     */
    public static String split(Object inS,int length){
    	String inStr = trim(inS);
    	if(isBank(inStr)){
    		return "";
    	}
    	if(inStr.length() > length){
    		return inStr.substring(0, length)+"...";
    	}else{
    		return inStr;
    	}
    }
    
    /**
     * 提供对 '  & 特殊符号的处理
     * @param inS
     * @return
     */
    public static String chr3839(Object inS){
        String inStr = trim(inS);
        if(isBank(inStr)){
            return "";
        }
        if(inStr.contains("'")){
            inStr=inStr.replace("'", "'||chr(39)||'");
        }
        if(inStr.contains("&")){
            inStr=inStr.replace("'", "'||chr(38)||'");
        }
        return inStr;
        
    }
    
    /**
     * 文件分隔符分割
     * @param filePath
     * @return
     */
    public static String pathTrim(String filePath){
    	if (File.separatorChar == '/') {
    		filePath = StringUtils.replace(filePath, "\\", "/");
        }
        else {
        	filePath = StringUtils.replace(filePath, "/", "\\");
        }
		return filePath;
    }
    
    /**
     * double 科学计数法
     * @param d
     * @return
     */
    public static String DoubleParse(Double d){
    	java.text.NumberFormat nf = java.text.NumberFormat.getInstance(); 
    	nf.setGroupingUsed(false);
    	return nf.format(d);
    }
    
    /**
     * 获取UUID字符串
     * @return
     */
    public static String getUUID(){
    	return UUID.randomUUID().toString().replace("-", "");
    }
    
    public static void main(String[] args) {
		System.out.println(getUUID());
	}
    
    /**
     * 改造poi默认的toString（）方法如下
    * @Title: getStringVal 
    * @Description: 1.对于不熟悉的类型，或者为空则返回""控制串
    *               2.如果是数字，则修改单元格类型为String，然后返回String，这样就保证数字不被格式化了
    * @param @param cell
    * @param @return    设定文件 
    * @return String    返回类型 
    * @throws
     */
    /*public static String getCellStringVal(Cell cell) {
        switch (cell.getCellType()) {
        case Cell.CELL_TYPE_BOOLEAN:
            return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
        case Cell.CELL_TYPE_FORMULA:
            return cell.getCellFormula();
        case Cell.CELL_TYPE_NUMERIC:
            cell.setCellType(Cell.CELL_TYPE_STRING);
            return cell.getStringCellValue();
        case Cell.CELL_TYPE_STRING:
            return cell.getStringCellValue();
        default:
            return "";
        }
    }*/
    
    
    /**
     * 将XML用Base64编码
     * 
     * @param xml
     * @return
     */
    public static String encode(String xml) {
        if (xml == null) {
            return null;
        }
        return com.example.auth2.util.Base64.encode(xml.getBytes());
    }
    
    public static String encode(String xml, String encode) throws UnsupportedEncodingException {
        if (xml == null) {
            return null;
        }
        return com.example.auth2.util.Base64.encode(xml.getBytes(encode));
    }
    
    /**
     * 将使用BASE64编码的字符串解码
     * 
     * @param str
     * @return
     */
    public static String decode(String str, String encode) {
        if (str == null) {
            return null;
        }
        byte[] bs = Base64.decode(str);
        try {
            return new String(bs, encode);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        // return new String(bs);
    }
    
    /**
     * 处理特殊字符
     * @param str
     * @return
     */
    public static String StringParse(String str) {
		 str = str.replace("<", "＜");
		 str = str.replace(">", "＞");
		 //str = str.replace("@", "＠");
		 str = str.replace("=", "＝");
		 str = str.replace("+", "＋");
		 str = str.replace("*", "＊");
		 str = str.replace("&", "＆");
		 str = str.replace("#", "＃");
		 str = str.replace("%", "％");
		 //str = str.replace("amp;", "＆");
		 //str = str.replace("＆rsquo;", "");
		return str;
    }
    
}
